package net.xfok.switches;

import java.util.ArrayList;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;

public class ToggleWidget extends AppWidgetProvider
{

	private Context _context;
	private RemoteViews _remoteViews;
	private SharedPreferences sp;
	private ArrayList<String> _btnClassArray;

	public static final int HANDLING_TYPE_DONE = 3;
	public static final int HANDLING_TYPE_IMMEDIATE = 2; // Means ToggleWidget
															// should update the
															// btnImgs after
															// TButton.canHandlerIntent()
															// And only works with intent starts with "armNclover.intent"
	public static final int HANDLING_TYPE_UNABLE = 1;

	private final int[] _layoutIDList = new int[] { R.layout.widgetlayout, R.layout.widgetlayout6b,
	                                               R.layout.widgetlayout7b};
	private final int[] _btnIdList = new int[] { R.id.Button1, R.id.Button2, R.id.Button3, R.id.Button4, R.id.Button5,
	                                            R.id.Button6, R.id.Button7 };
	private int _btnAmount = 5;
	
	private static TButton btnWifi,btnAirplane,btnAPN,btnBrightness,btnGPS,btnScreenAlwaysOn,btnSilent,btnSync,btnBluetooth,btnAutoRotate;

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
	{
		initWithPreference(context);
		updateButtonImg(appWidgetManager, appWidgetIds);
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		_context = null;
	}

	@Override
	public void onReceive(Context context, Intent intent)
	{
		initWithPreference(context);

		Log.i("Warwithinme",intent.getAction());
		TButton btn;
		if (intent.getAction().startsWith("net.xfok.switches"))
		{
			if (sp.getBoolean("press_vibrate", false))
			{
				Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
				vibrator.vibrate(50);
			}

			btn = getButtonByName(intent.getAction().substring(34));
			btn.toggleSetting(context);
			if (btn.canHandleIntent(intent) == ToggleWidget.HANDLING_TYPE_IMMEDIATE)
				updateButtonImg(null, null);

		} else
		{
			for (int i = 0; i < _btnAmount; ++i)
			{
				btn = getButtonByName(_btnClassArray.get(i));
				if (btn.canHandleIntent(intent) == HANDLING_TYPE_DONE)
				{
					updateButtonImg(null, null);
					break;
				}
			}
		}

		super.onReceive(context, intent);
		_context = null;
	}

	private void initWithPreference(Context context)
	{
		_context = context;

		if (sp == null)
			sp = PreferenceManager.getDefaultSharedPreferences(_context);

		int _btnAmount_new = Integer.parseInt(sp.getString("btn_amount", "5"));
		boolean layoutChanged = (_btnAmount_new != _btnAmount);
		_btnAmount = _btnAmount_new;
		if (_remoteViews == null || layoutChanged)
			_remoteViews = new RemoteViews(_context.getPackageName(), _layoutIDList[_btnAmount - 5]);

		if (_btnClassArray == null)
		{
			_btnClassArray = new ArrayList<String>();
			_btnClassArray.add(sp.getString("Button1", "ButtonWifi"));
			_btnClassArray.add(sp.getString("Button2", "ButtonAPN"));
			_btnClassArray.add(sp.getString("Button3", "ButtonAirplane"));
			_btnClassArray.add(sp.getString("Button4", "ButtonScreenAlwaysOn"));
			_btnClassArray.add(sp.getString("Button5", "ButtonSilent"));
			_btnClassArray.add(sp.getString("Button6", "ButtonAutoRotate"));
			_btnClassArray.add(sp.getString("Button7", "ButtonSync"));
		}
	}

	// Replace java relectioin
	private TButton getButtonByName(String name)
	{
		if (name.equals("ButtonWifi"))
			return (btnWifi != null)?btnWifi:(btnWifi = new ButtonWifi());
		else if (name.equals("ButtonAPN"))
			return (btnAPN !=null)?btnAPN:(btnAPN = new ButtonAPN());
		else if (name.equals("ButtonAirplane"))
			return (btnAirplane!=null)?btnAirplane:(btnAirplane = new ButtonAirplane());
		else if (name.equals("ButtonSilent"))
			return (btnSilent != null)?btnSilent:(btnSilent = new ButtonSilent());
		else if (name.equals("ButtonScreenAlwaysOn"))
			return (btnScreenAlwaysOn != null)?btnScreenAlwaysOn:(btnScreenAlwaysOn = new ButtonScreenAlwaysOn());
		else if (name.equals("ButtonBrightness"))
			return (btnBrightness != null)?btnBrightness:(btnBrightness = new ButtonBrightness());
		else if (name.equals("ButtonBluetooth"))
			return (btnBluetooth != null)?btnBluetooth:(btnBluetooth = new ButtonBluetooth());
		else if (name.equals("ButtonGPS"))
			return (btnGPS != null)?btnGPS:(btnGPS = new ButtonGPS());
		else if (name.equals("ButtonAutoRotate"))
			return (btnAutoRotate != null)?btnAutoRotate:(btnAutoRotate = new ButtonAutoRotate());
		else// if(name.equals("ButtonSync"))
			return (btnSync != null)?btnSync:(btnSync = new ButtonSync());
	}

	private void updateButtonImg(AppWidgetManager manager, int[] appWidgetIds)
	{
		for (int i = 0; i < _btnAmount; ++i)
		{
			TButton btn = getButtonByName(_btnClassArray.get(i));
			Intent myIntent = new Intent(btn.getIntentAction());
			PendingIntent pintent = PendingIntent.getBroadcast(_context, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
			int buttonImgResource = btn.getButtonBmp(_context);

			_remoteViews.setOnClickPendingIntent(_btnIdList[i], pintent);
			_remoteViews.setImageViewResource(_btnIdList[i], buttonImgResource);
		}

		if (manager == null)
			manager = AppWidgetManager.getInstance(_context);
		if (appWidgetIds != null)
			manager.updateAppWidget(appWidgetIds, _remoteViews);
		else
			manager.updateAppWidget(new ComponentName(_context, ToggleWidget.class), _remoteViews);
	}
}
